﻿using System;
using ch10.binary;
using ch10.binary.type;
using ch10.instance;

namespace ch10.interpreter
{
    public struct Table : ITable
    {
        public TableType _type;
        public IFunction[] Elems;

        public Table(TableType tt)
        {
            _type = tt;
            Elems = new IFunction[tt.Limits.Min];
        }

        public void Grow(uint n)
        {
            var newElems = new IFunction[Elems.Length + n];
            Array.Copy(newElems, 0, Elems, 0, Elems.Length);
            Elems = newElems;
        }

        public IFunction GetElem(uint idx)
        {
            CheckIdx(idx);
            var elem = Elems[idx];
            return elem;
        }

        public TableType Type()
        {
            return _type;
        }

        public uint Size()
        {
            return (uint) (Elems.Length);
        }

        public void SetElem(uint idx, IFunction elem)
        {
            CheckIdx(idx);
            Elems[idx] = elem;
        }

        private void CheckIdx(uint idx)
        {
            if (idx >= (uint) (Elems.Length))
            {
                Panic.Run(Errors.ErrUndefinedElem);
            }
        }
    }
}